import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Save, X, Plus, Trash2, ThumbsDown } from "lucide-react";

const StringArrayEditor = ({ title, items, onUpdate, placeholder }) => {
  const safeItems = Array.isArray(items) ? items : [];
  const handleAddItem = () => onUpdate([...safeItems, ""]);
  const handleUpdateItem = (index, value) => {
    const newItems = [...safeItems];
    newItems[index] = value;
    onUpdate(newItems);
  };
  const handleRemoveItem = (index) => {
    onUpdate(safeItems.filter((_, i) => i !== index));
  };

  return (
    <div className="space-y-3 p-4 border rounded-lg bg-gray-50/50">
      <h4 className="font-medium text-gray-800">{title}</h4>
      <div className="space-y-2">
        {safeItems.map((item, index) => (
          <div key={index} className="flex items-center gap-2">
            <Textarea
              value={item}
              onChange={(e) => handleUpdateItem(index, e.target.value)}
              placeholder={`${placeholder} ${index + 1}`}
              rows={2}
            />
            <Button
              variant="ghost"
              size="icon"
              onClick={() => handleRemoveItem(index)}
              className="text-red-500 hover:text-red-700 shrink-0"
            >
              <Trash2 className="w-4 h-4" />
            </Button>
          </div>
        ))}
      </div>
      {/* <Button variant="outline" size="sm" onClick={handleAddItem} className="bg-white">
            <Plus className="w-4 h-4 mr-2" /> 添加条目
        </Button> */}

      <Button
        variant="outline"
        size="sm"
        onClick={(e) => {
          e.stopPropagation(); // 阻止冒泡到父元素
          e.preventDefault(); // 阻止默认行为（如果有）
          handleAddItem();
        }}
        className="bg-white"
      >
        <Plus className="w-4 h-4 mr-2" /> 添加条目
      </Button>
    </div>
  );
};

export default function QualityIssueForm({ issue, onSubmit, onCancel }) {
  const [localIssue, setLocalIssue] = useState({});

  useEffect(() => {
    setLocalIssue(
      issue || {
        issueName: "",
        category: "",
        preventionMeasures: [],
        responsibleRoles: [],
      }
    );
  }, [issue]);

  const handleFieldChange = (field, value) => {
    setLocalIssue((prev) => ({ ...prev, [field]: value }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    onSubmit(localIssue);
  };

  return (
    <Card className="mb-6 shadow-lg border-red-200" id="quality-issue-form">
      <CardHeader className="bg-red-50">
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <ThumbsDown className="w-5 h-5 text-red-600" />
            {issue ? `编辑质量通病: ${issue.issueName}` : "新建质量通病"}
          </span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium mb-1">
                防治项目名称
              </label>
              <Input
                value={localIssue.issueName || ""}
                onChange={(e) => handleFieldChange("issueName", e.target.value)}
                placeholder="例如: 导线磨损防治"
                required
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">通病分类</label>
              <Input
                value={localIssue.category || ""}
                onChange={(e) => handleFieldChange("category", e.target.value)}
                placeholder="例如: 架线工程"
              />
            </div>
          </div>

          <StringArrayEditor
            title="主要防治措施"
            items={localIssue.preventionMeasures || []}
            onUpdate={(value) => handleFieldChange("preventionMeasures", value)}
            placeholder="请输入防治措施"
          />

          <StringArrayEditor
            title="责任人角色"
            items={localIssue.responsibleRoles || []}
            onUpdate={(value) => handleFieldChange("responsibleRoles", value)}
            placeholder="请输入责任人角色"
          />

          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" className="bg-red-600 hover:bg-red-700">
              <Save className="w-4 h-4 mr-2" />
              保存
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}
